package tzjz.example.util;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xhtmlrenderer.swing.Java2DRenderer;
import org.xhtmlrenderer.util.FSImageWriter;
 
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Map;
/**
 * @author zhuling
 * @Description
 * @create 2021-07-14 15:40
 */
public class FreemarkeTools {
    private static final Logger logger = LoggerFactory.getLogger(FreemarkeTools.class);
 
    private static final String encoding = "UTF-8";
 
    /**
     * 获取模板转为html
     */
    public static String ftlToString(Map<String,Object> map, String templateName) throws IOException, TemplateException {
        String value = "";
        Configuration configuration = new Configuration();
        // linux环境用不了
//        Resource resource = new ClassPathResource("templates");
//        File sourceFile =  resource.getFile();
//        String ftlPath = sourceFile.getAbsolutePath();
 
        StringWriter out = new StringWriter();

        configuration.setDirectoryForTemplateLoading(new File("src/main/resources/templates"));
        configuration.unsetCacheStorage();
        Template template = configuration.getTemplate(templateName,encoding);
        template.setEncoding(encoding);
        template.process(map, out);
        out.flush();
        out.close();
        value = out.getBuffer().toString();
 
//        logger.info("模板文件html内容为：======="+value);
        return value;
    }
 
    /**
     * html转为图片
     * @param html
     * @param inputFileName
     * @param outputFileName
     * @param widthImage
     * @param heightImage
     * @return
     * @throws IOException
     */
    public static String turnImage(String html, String inputFileName, String outputFileName
            ,int widthImage, int heightImage) throws IOException {
        BufferedWriter bufferedWriter = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(inputFileName),encoding));
        bufferedWriter.write(html);
        bufferedWriter.newLine();
        bufferedWriter.flush();
        bufferedWriter.close();
 
        File f = new File(inputFileName);
        Java2DRenderer renderer = new Java2DRenderer(f, widthImage, heightImage);
        BufferedImage image = renderer.getImage();
        FSImageWriter imageWriter = new FSImageWriter();
        imageWriter.setWriteCompressionQuality(0.9f);
        File imgFile = new File(outputFileName);
        FileOutputStream fout = new FileOutputStream(imgFile);
        imageWriter.write(image, fout);
        fout.close();
        return outputFileName;
    }
}